package com.ty.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/order2")
@Slf4j
public class OrderingController2 {
    @GetMapping
    @SentinelResource(value = "ordering2",fallback="ordering_fallback")//资源名称叫ordering
    public String ordering(@RequestParam Integer userId) {
        log.debug("正常业务请求进来了");
        if(userId.equals(4)){
            int i = 5/0;
        }
        return "你真正喜欢的商品";
    }
    public static String ordering_fallback(Integer userId, Throwable  exception) {
        log.debug("降级请求进来了");
        //兜底
        return "随机的商品";
    }
     //降级配置规则
    @PostConstruct
    public static void initDegradeRules() {
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource("ordering2"); //设置资源名称
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT); // 异常率
        rule.setCount(2);//// 异常数量
        rule.setTimeWindow(10); // 熔断时长10s
        rule.setMinRequestAmount(5);// 单位时长的最小请求数 与下面的配置结合一起使用
        rule.setStatIntervalMs(10*1000);// 10s 统计时长,统计的窗口（单位为 ms） 表示每10秒统计一次异常率。
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }

}
